<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 用户行为日志
 */
class UserActLog extends Model
{
    protected $table = 'user_act_log';
    protected $fillable = [
        'user_id', 'act', 'flag', 'detail'
    ];

    //正常
    const FLAG_OK = 1;
    //不可操作
    const FLAG_NO = 0;
    //违规
    const FLAG_BAD = -1;
    const FLAG_ING = 2;

    const FLAG = [
        self::FLAG_OK => '正常',
        self::FLAG_NO => '不可操作',
        self::FLAG_BAD => '违规',
        self::FLAG_ING => '待审核',
    ];

    //上线
    const ACT_ONLINE = 1;
    //离线
    const ACT_OFFLINE = 0;
    //提交头像
    const ACT_AVATAR = 2;

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    public function personalProfile()
    {
        return $this->belongsTo(UserProfilePersonal::class, 'user_id', 'user_id');
    }

    /**
     * 获取最新一条记录
     */
    static function getLastItem($userId = 0)
    {
        return self::where('user_id', $userId)->orderBy('id', 'desc')->first();
    }

    /**
     * 最近一张有效头像
     */
    static function getLatestAvatar($userId = 0)
    {
        $where = [
            'user_id' => $userId,
            'act' => self::ACT_AVATAR,
            // 'flag' => self::FLAG_OK
        ];
        return self::where($where)->whereIn('flag', [self::FLAG_NO, self::FLAG_OK])->orderBy('id', 'desc')->first();
    }

    /**
     * 计算数组内多少
     */
    static function checkActiveCount($userIds = [], $startTime = '', $endTime = '', $channel = '')
    {
        $where = [];
        //指定注册渠道
        if (!$channel) {
            $table = 'user_act_log';
            if ($startTime) $where[] = [$table . '.created_at', '>=', $startTime];
            if ($endTime) $where[] = [$table . '.created_at', '<', $endTime];
            $query = self::where($where);
        } else {
            $table = 'user_act_log';
            if ($startTime) $where[] = [$table . '.created_at', '>=', $startTime];
            if ($endTime) $where[] = [$table . '.created_at', '<', $endTime];
            $query = DB::table($table)->join('user', function ($join) use ($channel, $where, $table) {
                $where[] = ['channel', $channel];
                $join->on($table . '.user_id', '=', 'user.id')->where($where);
            });
        }

        //指定用户集
        if ($userIds) {
            $data = $query->whereIn('user_id', $userIds)->select(Db::raw('count(distinct user_id) as ctn'))->first();
        } else {
            $data = $query->select(DB::raw('count(distinct user_id) as ctn'))->first();
        }
        return $data && $data->ctn ? $data->ctn : 0;
    }
}
